package com.oss.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author 王霄
 * @date 2022/8/29 15:44
 */
@AllArgsConstructor
@Slf4j
public class OssDefaultClient implements OssClient {
    private final OSS oss;
    private final OssProperties ossProperties;

    @Override
    public OssFileResponse uploadFile(OssFileRequest request) {
        Assert.notNull(request.getFile(), "上传文件不能为空");
        try {
            //原始文件名
            String originName = request.getFile().getOriginalFilename();
            //文件类型
            String fileType = FileUtil.extName(originName);
            //文件名
            String fileName = Optional.ofNullable(request.getFileName()).orElse(IdUtil.simpleUUID()) + StrUtil.DOT + fileType;
            //文件大小
            Long size = request.getFile().getSize();
            //桶名
            String bucketName = ossProperties.getBucketName();
            //文件流
            InputStream inputStream = request.getFile().getInputStream();
            //上传文件
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(request.getFile().getContentType());
            String filePath = String.format("%s", fileName);
            oss.putObject(bucketName, filePath, inputStream, objectMetadata);
            //获取文件上传地址
            String fileUrl = String.format("https://%s.%s/%s", bucketName, ossProperties.getEndpoint(), filePath);
            return OssFileResponse.builder()
                    .fileName(fileName)
                    .originName(originName)
                    .fileType(fileType)
                    .filSize(size)
                    .fileUrl(fileUrl)
                    .build();
        } catch (
                IOException e) {
            log.error("OSS文件上传失败: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
